/**
 * Prompt分析工具 - 用于分析和展示Prompt的层级结构
 */

export interface PromptLayer {
  id: number;
  type: 'Template' | 'System' | 'Smart' | 'Frontend' | 'User';
  name: string;
  source: string;
  function: string;
  content: string;
  length: number;
  priority: number;
}

export interface PromptAnalysis {
  layers: PromptLayer[];
  totalLength: number;
  mergeStrategy: string;
  finalPrompt: string;
  statistics: {
    layerCount: number;
    averageLength: number;
    longestLayer: PromptLayer;
    shortestLayer: PromptLayer;
  };
}

/**
 * 分析Prompt结构
 */
export function analyzePromptStructure(
  templatePrompt: string,
  systemPrompt: string,
  smartPrompt: string,
  frontendPrompt: string,
  userPrompt: string,
  finalPrompt: string
): PromptAnalysis {
  
  const layers: PromptLayer[] = [
    {
      id: 1,
      type: 'Template',
      name: 'Template Prompt (模板提示词)',
      source: '预定义模板',
      function: '角色定义、风格控制',
      content: templatePrompt,
      length: templatePrompt.length,
      priority: 1
    },
    {
      id: 2,
      type: 'System',
      name: 'System Prompt (系统提示词)',
      source: '后端系统生成',
      function: '规范约束、上下文',
      content: systemPrompt,
      length: systemPrompt.length,
      priority: 2
    },
    {
      id: 3,
      type: 'Smart',
      name: 'Smart Prompt (智能提示词)',
      source: 'AI智能生成',
      function: '任务指导、智能建议',
      content: smartPrompt,
      length: smartPrompt.length,
      priority: 3
    },
    {
      id: 4,
      type: 'Frontend',
      name: 'Frontend Prompt (界面提示词)',
      source: '前端界面设置',
      function: '界面层要求',
      content: frontendPrompt,
      length: frontendPrompt.length,
      priority: 4
    },
    {
      id: 5,
      type: 'User',
      name: 'User Input (用户输入)',
      source: '用户直接输入',
      function: '个性化要求',
      content: userPrompt,
      length: userPrompt.length,
      priority: 5
    }
  ];

  const totalLength = finalPrompt.length;
  const layerCount = layers.length;
  const averageLength = Math.round(layers.reduce((sum, layer) => sum + layer.length, 0) / layerCount);
  
  const sortedByLength = [...layers].sort((a, b) => b.length - a.length);
  const longestLayer = sortedByLength[0];
  const shortestLayer = sortedByLength[sortedByLength.length - 1];

  return {
    layers,
    totalLength,
    mergeStrategy: '顺序叠加，优先级递增',
    finalPrompt,
    statistics: {
      layerCount,
      averageLength,
      longestLayer,
      shortestLayer
    }
  };
}

/**
 * 打印Prompt分析结果
 */
export function printPromptAnalysis(analysis: PromptAnalysis): void {
  console.log('=== 📊 Prompt结构分析 ===');
  console.log('');
  
  // 打印各层详情
  analysis.layers.forEach((layer, index) => {
    const emoji = getLayerEmoji(layer.type);
    console.log(`${emoji} [${layer.id}] ${layer.name}:`);
    console.log(`   来源: ${layer.source}`);
    console.log(`   功能: ${layer.function}`);
    console.log(`   长度: ${layer.length} 字符`);
    console.log(`   优先级: ${layer.priority}`);
    console.log(`   内容预览: ${layer.content.substring(0, 100)}${layer.content.length > 100 ? '...' : ''}`);
    console.log('');
  });

  // 打印统计信息
  console.log('📈 统计信息:');
  console.log(`   总层数: ${analysis.statistics.layerCount}`);
  console.log(`   平均长度: ${analysis.statistics.averageLength} 字符`);
  console.log(`   最长层: ${analysis.statistics.longestLayer.name} (${analysis.statistics.longestLayer.length} 字符)`);
  console.log(`   最短层: ${analysis.statistics.shortestLayer.name} (${analysis.statistics.shortestLayer.length} 字符)`);
  console.log(`   合并策略: ${analysis.mergeStrategy}`);
  console.log(`   最终长度: ${analysis.totalLength} 字符`);
  console.log('');
}

/**
 * 获取层级对应的emoji
 */
function getLayerEmoji(type: PromptLayer['type']): string {
  const emojiMap = {
    'Template': '📝',
    'System': '🔧', 
    'Smart': '🤖',
    'Frontend': '🖥️',
    'User': '👤'
  };
  return emojiMap[type] || '📄';
}

/**
 * 生成Prompt层级图表
 */
export function generatePromptChart(analysis: PromptAnalysis): string {
  const maxLength = Math.max(...analysis.layers.map(l => l.length));
  
  let chart = '\n=== 📊 Prompt层级结构图 ===\n\n';
  chart += '层级 | 类型           | 长度     | 占比    | 可视化\n';
  chart += '-----|----------------|----------|---------|------------------\n';
  
  analysis.layers.forEach(layer => {
    const percentage = Math.round((layer.length / analysis.totalLength) * 100);
    const barLength = Math.round((layer.length / maxLength) * 20);
    const bar = '█'.repeat(barLength) + '░'.repeat(20 - barLength);
    
    chart += `  ${layer.id}  | ${layer.type.padEnd(14)} | ${layer.length.toString().padStart(6)} | ${percentage.toString().padStart(5)}% | ${bar}\n`;
  });
  
  chart += '\n';
  chart += `总计: ${analysis.totalLength} 字符\n`;
  chart += `合并策略: ${analysis.mergeStrategy}\n`;
  
  return chart;
}

/**
 * 验证Prompt质量
 */
export function validatePromptQuality(analysis: PromptAnalysis): {
  score: number;
  issues: string[];
  suggestions: string[];
} {
  const issues: string[] = [];
  const suggestions: string[] = [];
  let score = 100;

  // 检查长度
  if (analysis.totalLength > 4000) {
    issues.push('Prompt总长度过长，可能影响AI理解');
    suggestions.push('考虑精简部分内容或分段处理');
    score -= 10;
  }

  if (analysis.totalLength < 100) {
    issues.push('Prompt总长度过短，可能缺少必要信息');
    suggestions.push('增加更多上下文和指导信息');
    score -= 15;
  }

  // 检查层级平衡
  const lengthVariance = analysis.layers.reduce((sum, layer) => {
    const diff = layer.length - analysis.statistics.averageLength;
    return sum + (diff * diff);
  }, 0) / analysis.layers.length;

  if (lengthVariance > 10000) {
    issues.push('各层级长度差异过大，可能导致重点不均');
    suggestions.push('平衡各层级的内容长度');
    score -= 5;
  }

  // 检查用户输入
  const userLayer = analysis.layers.find(l => l.type === 'User');
  if (userLayer && userLayer.length < 20) {
    issues.push('用户输入过短，可能缺少具体要求');
    suggestions.push('鼓励用户提供更详细的创作要求');
    score -= 10;
  }

  return {
    score: Math.max(0, score),
    issues,
    suggestions
  };
}

/**
 * 导出Prompt分析报告
 */
export function exportPromptReport(analysis: PromptAnalysis): string {
  const quality = validatePromptQuality(analysis);
  const chart = generatePromptChart(analysis);
  
  let report = '# Prompt分析报告\n\n';
  report += `生成时间: ${new Date().toLocaleString()}\n\n`;
  
  report += '## 基本信息\n';
  report += `- 总层数: ${analysis.statistics.layerCount}\n`;
  report += `- 总长度: ${analysis.totalLength} 字符\n`;
  report += `- 平均长度: ${analysis.statistics.averageLength} 字符\n`;
  report += `- 合并策略: ${analysis.mergeStrategy}\n\n`;
  
  report += '## 层级详情\n';
  analysis.layers.forEach(layer => {
    report += `### ${layer.name}\n`;
    report += `- 来源: ${layer.source}\n`;
    report += `- 功能: ${layer.function}\n`;
    report += `- 长度: ${layer.length} 字符\n`;
    report += `- 优先级: ${layer.priority}\n\n`;
  });
  
  report += '## 结构图表\n';
  report += '```\n' + chart + '```\n\n';
  
  report += '## 质量评估\n';
  report += `- 质量评分: ${quality.score}/100\n\n`;
  
  if (quality.issues.length > 0) {
    report += '### 发现的问题\n';
    quality.issues.forEach(issue => {
      report += `- ${issue}\n`;
    });
    report += '\n';
  }
  
  if (quality.suggestions.length > 0) {
    report += '### 改进建议\n';
    quality.suggestions.forEach(suggestion => {
      report += `- ${suggestion}\n`;
    });
    report += '\n';
  }
  
  return report;
}
